#include"Heap.h"

void Swap(HPDataType* x, HPDataType* y)
{
	HPDataType temp = *x;
	*x = *y;
	*y = temp;
}

void HeapExpansion(HP* php)
{
	assert(php);
	int newCapacity = php->capacity == 0 ? 4 : php->capacity * 2;
	HPDataType* tmp = (HPDataType*)realloc(php->a, sizeof(HPDataType) * newCapacity);
	if (tmp == NULL)
	{
		perror("malloc Failed");
		exit(-1);
	}
	php->a = tmp;
	php->capacity = newCapacity;
}

void HeapInit(HP* php)
{
	assert(php);
	php->a = NULL;
	php->capacity = php->size = 0;
}


void HeapDestory(HP* php)
{
	assert(php);
	free(php->a);
	php->a = NULL;
	php->capacity = php->size = 0;
}

void AdjustUp(HPDataType* a,int n)
{
	int child = n-1;
	int parent = (child - 1) / 2;
	while (child)
	{
		if (a[child] < a[parent])
		{
			Swap(&(a[child]), &(a[parent]));
			child = parent;
			parent = (parent - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void HeapPush(HP* php, HPDataType x)
{
	if (php->capacity == php->size)
	{
		HeapExpansion(php);
	}
	php->a[php->size++] = x;
	AdjustUp(php->a, php->size, x);
}

void HeapPrint(HP* php)
{
	assert(php);
	for (int i = 0; i < php->size; i++)
		printf("%d   ", php->a[i]); 
	printf("\n");
}

void AdjustDown(HPDataType* a, int n)
{
	assert(a);
	int parent = 0;
	int lchild = parent * 2 + 1;
	int min = lchild;
	while (min < n)
	{
		if (lchild + 1 <  n && a[lchild] > a[lchild + 1])
		{
			min = lchild + 1;
		}
		if (a[parent] > a[min])
		{
			Swap(&(a[parent]), &(a[min]));
			parent = min;
			min = min * 2 + 1;
		}
		else
		{
			break;
		}
	}

}

void HeapPop(HP* php)
{
	assert(php);
	assert(php->size > 0);
	int n = php->size;
	Swap(&(php->a[0]), &(php->a[n - 1]));
	AdjustDown( php->a, n-1);
	--php->size;
}

HPDataType HeapTop(HP* hp)
{
	assert(hp);
	assert(hp->size);
	return   hp->a[0];
}

bool HeapEmpty(HP* hp)
{ 
	assert(hp);
	return hp->size == 0;
}


void HeapInitArray(HP* hp, HPDataType* a, int n)
{
	hp->a = (HPDataType*)malloc(sizeof(HPDataType) * n);
	if (hp->a == NULL)
	{
		perror("malloc failed");
		exit(-1);
	}
	hp->capacity = hp->size = 0;
	memcpy(hp->a, a, sizeof(HPDataType)*n);
	for (int i = 1; i < n; i++)
	{
		AdjustUp(hp->a, i);
	}
}



